import connection from './jsstore_con';
import { infoDefault } from './mateDbConst';
import { cloneDeep } from 'lodash';

//获取本地数据库信息
function checkJsStore() {
  return indexedDB.databases().then(retList => {
    const tmpDb = retList.find(item => {
      return item.name === infoDefault.name;
    });
    if (tmpDb) {
      return connection.openDb(tmpDb.name, tmpDb.version);
    } else {
      const retObj = cloneDeep(infoDefault);
      connection.initDb(retObj);
      return retObj;
    }
  });
}

function _columnListToMap(params) {
  const columns = {};
  params.forEach(item => {
    columns[item.name] = item;
  });
  return columns;
}

// 创建表结构
function createTable(dbInfo, param) {
  const newDbInfo = cloneDeep(dbInfo);
  newDbInfo.tables = [];
  // 将现有表结构转成创建格式
  dbInfo.tables.forEach(item => {
    if (item.name !== 'JsStore_Meta') {
      newDbInfo.tables.push({
        name: item.name,
        columns: _columnListToMap(item.columns),
      });
    }
  });
  // 添加新的表结构
  newDbInfo.tables.push({
    name: param.name,
    columns: _columnListToMap(param.columns),
  });
  // 更新版本号
  newDbInfo.version++;
  return connection.initDb(newDbInfo);
}

// 删除表结构
function dropTable(dbInfo, tableName) {
  const newDbInfo = cloneDeep(dbInfo);
  newDbInfo.tables = [];
  // 将现有表结构转成创建格式，并过滤删除的表
  dbInfo.tables.forEach(item => {
    if (item.name !== 'JsStore_Meta' && item.name !== tableName) {
      newDbInfo.tables.push({
        name: item.name,
        columns: _columnListToMap(item.columns),
      });
    }
  });
  // 更新版本号
  newDbInfo.version++;
  return connection.initDb(newDbInfo);
}

function insertData(dbInfo, tableName, param) {
  return connection.insert({
    into: tableName,
    values: param,
  });
}

function queryTable(dbInfo, tableName, param) {
  return connection.select({
    from: tableName
  });
}

function countTable(dbInfo, tableName, param) {
  return connection.count({
    from: tableName
  });
}

export {
  checkJsStore,
  createTable,
  dropTable,
  insertData,
  queryTable,
  countTable
};